package com.ilxqx.fierce.action;

import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ilxqx.fierce.core.*;
import com.ilxqx.fierce.exception.FierceRequestException;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 获取单条数据处理器
 *
 * @author Venus
 * @since 1.0.0
 */
@Component
public class GetOneActionHandler implements CommonActionHandler {
    /**
     * 处理动作
     *
     * @param action      动作
     * @param requestData 请求数据
     * @return 响应对象
     */
    @Override
    public FierceResponse handle(String action, Map<String, Object> requestData) {
        FierceRequestContext context = FierceRequestContextHolder.get();

        if (!requestData.containsKey("id")) {
            throw new FierceRequestException("参数ID必须！");
        }

        List<?> objects = ReflectUtil.invoke(
            context.getMapper(),
            ReflectUtil.getMethod(BaseMapper.class, "selectById", Serializable.class),
            new Object[]{requestData.get("id")}
        );

        return FierceResponse.succeed(objects);
    }

    /**
     * 是否支持
     *
     * @param candidate 候选者
     * @return bool
     */
    @Override
    public boolean supports(String candidate) {
        return CommonAction.GET_ONE.getAction().equals(candidate);
    }
}
